package com.dc.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;

public class Base64DecodeMultipartFile implements MultipartFile {
    private final byte[] imgContent;


    public Base64DecodeMultipartFile(byte[] imgContent) {
        this.imgContent = imgContent;

    }

    @Override
    public String getName() {
        return System.currentTimeMillis() + Math.random() + "." + "jpeg";
    }

    @Override
    public String getOriginalFilename() {
        return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + "jpeg";
    }

    @Override
    public String getContentType() {
        return "image";
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(imgContent);
    }


    /**
     * base64转multipartFile
     *
     * @param base64
     * @return
     */
    public static MultipartFile base64Convert(String base64) {


        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b = new byte[0];
        try {
            b = decoder.decodeBuffer(base64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        return new Base64DecodeMultipartFile(b);
    }

    public static MultipartFile toMultipartFile(String fieldName, File file) throws Exception {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        String contentType = new MimetypesFileTypeMap().getContentType(file);
        FileItem fileItem = diskFileItemFactory.createItem(fieldName, contentType, false, file.getName());

        try (InputStream inputStream = new ByteArrayInputStream(FileCopyUtils.copyToByteArray(file));
             OutputStream outputStream = fileItem.getOutputStream()) {
            FileCopyUtils.copy(inputStream, outputStream);

        } catch (Exception e) {
            throw e;
        }
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    /**
     * 读取文件内容
     *
     * @param multipartFile
     * @return
     */
    public static String fileContentReading(MultipartFile multipartFile) {
        String s = "";
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(new FileInputStream(file), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while (true) {
            try {
                if (!((s = br.readLine()) != null)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            content = content.append(s);
        }
        try {
            br.close();
            in.close();
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
}
